
<!DOCTYPE html>

<html>
  
<!-- Mirrored from docs.sympy.org/latest/tutorial/manipulation.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 15 Jan 2022 03:23:58 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack -->
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>Advanced Expression Manipulation &#8212; SymPy 1.9 documentation</title>
    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/default.css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
    <link rel="stylesheet" type="text/css" href="../../../live.sympy.org/static/live-core.css" />
    <link rel="stylesheet" type="text/css" href="../../../live.sympy.org/static/live-autocomplete.css" />
    <link rel="stylesheet" type="text/css" href="../../../live.sympy.org/static/live-sphinx.css" />
    
    <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
    <script src="../_static/jquery.js"></script>
    <script src="../_static/underscore.js"></script>
    <script src="../_static/doctools.js"></script>
    <script src="../../../live.sympy.org/static/utilities.js"></script>
    <script src="../../../live.sympy.org/static/external/classy.js"></script>
    <script src="../../../live.sympy.org/static/live-core.js"></script>
    <script src="../../../live.sympy.org/static/live-autocomplete.js"></script>
    <script src="../../../live.sympy.org/static/live-sphinx.js"></script>
    <script async="async" src="../../../cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest8331.js?config=TeX-AMS_HTML-full"></script>
    <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]]}})</script>
    
    <link rel="shortcut icon" href="../_static/sympy-notailtext-favicon.ico"/>
    <link href="manipulation.html" rel="canonical" />
    
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="SymPy Guides" href="../guides/index.html" />
    <link rel="prev" title="Matrices" href="matrices.html" /> 
  </head><body>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../guides/index.html" title="SymPy Guides"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="matrices.html" title="Matrices"
             accesskey="P">previous</a> |</li>
        <li class="nav-item nav-item-0"><a href="../index.html">SymPy 1.9 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">SymPy Tutorial</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="#">Advanced Expression Manipulation</a></li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <section id="advanced-expression-manipulation">
<span id="tutorial-manipulation"></span><h1>Advanced Expression Manipulation<a class="headerlink" href="#advanced-expression-manipulation" title="Permalink to this headline">¶</a></h1>
<p>In this section, we discuss some ways that we can perform advanced
manipulation of expressions.</p>
<section id="understanding-expression-trees">
<h2>Understanding Expression Trees<a class="headerlink" href="#understanding-expression-trees" title="Permalink to this headline">¶</a></h2>
<aside class="sidebar">
<p class="sidebar-title">Quick Tip</p>
<p>To play with the <code class="docutils literal notranslate"><span class="pre">srepr</span></code> form of expressions in the SymPy Live shell,
change the output format to <code class="docutils literal notranslate"><span class="pre">Repr</span></code> in the settings.</p>
</aside>
<p>Before we can do this, we need to understand how expressions are represented
in SymPy.  A mathematical expression is represented as a tree.  Let us take
the expression <span class="math notranslate nohighlight">\(x^2 + xy\)</span>, i.e., <code class="docutils literal notranslate"><span class="pre">x**2</span> <span class="pre">+</span> <span class="pre">x*y</span></code>.  We can see what this
expression looks like internally by using <code class="docutils literal notranslate"><span class="pre">srepr</span></code></p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">symbols</span><span class="p">(</span><span class="s1">&#39;x y z&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="go">&quot;Add(Pow(Symbol(&#39;x&#39;), Integer(2)), Mul(Symbol(&#39;x&#39;), Symbol(&#39;y&#39;)))&quot;</span>
</pre></div>
</div>
<p>The easiest way to tear this apart is to look at a diagram of the expression
tree:</p>
<div class="graphviz"><object data="../_images/graphviz-d6cfeb1f975b9a36682b7d430767a2c103d8e138.svg" type="image/svg+xml" class="graphviz">
<p class="warning">digraph{

# Graph style
&quot;ordering&quot;=&quot;out&quot;
&quot;rankdir&quot;=&quot;TD&quot;

#########
# Nodes #
#########

&quot;Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))_()&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Add&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Pow(Symbol('x'), Integer(2))_(0,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Pow&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol('x')_(0, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Integer(2)_(0, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(2)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(Symbol('x'), Symbol('y'))_(1,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol('x')_(1, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol('y')_(1, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('y')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];

#########
# Edges #
#########

&quot;Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))_()&quot; -&gt; &quot;Pow(Symbol('x'), Integer(2))_(0,)&quot;;
&quot;Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))_()&quot; -&gt; &quot;Mul(Symbol('x'), Symbol('y'))_(1,)&quot;;
&quot;Pow(Symbol('x'), Integer(2))_(0,)&quot; -&gt; &quot;Symbol('x')_(0, 0)&quot;;
&quot;Pow(Symbol('x'), Integer(2))_(0,)&quot; -&gt; &quot;Integer(2)_(0, 1)&quot;;
&quot;Mul(Symbol('x'), Symbol('y'))_(1,)&quot; -&gt; &quot;Symbol('x')_(1, 0)&quot;;
&quot;Mul(Symbol('x'), Symbol('y'))_(1,)&quot; -&gt; &quot;Symbol('y')_(1, 1)&quot;;
}</p></object></div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The above diagram was made using <a class="reference external" href="http://www.graphviz.org/">Graphviz</a> and
the <a class="reference internal" href="../modules/printing.html#sympy.printing.dot.dotprint" title="sympy.printing.dot.dotprint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dotprint</span></code></a> function.</p>
</div>
<p>First, let’s look at the leaves of this tree.  Symbols are instances of the
class Symbol.  While we have been doing</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">symbols</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>we could have also done</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">Symbol</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Either way, we get a Symbol with the name “x” <a class="footnote-reference brackets" href="#symbols-fn" id="id1">1</a>.  For the number in the
expression, 2, we got <code class="docutils literal notranslate"><span class="pre">Integer(2)</span></code>.  <code class="docutils literal notranslate"><span class="pre">Integer</span></code> is the SymPy class for
integers.  It is similar to the Python built-in type <code class="docutils literal notranslate"><span class="pre">int</span></code>, except that
<code class="docutils literal notranslate"><span class="pre">Integer</span></code> plays nicely with other SymPy types.</p>
<p>When we write <code class="docutils literal notranslate"><span class="pre">x**2</span></code>, this creates a <code class="docutils literal notranslate"><span class="pre">Pow</span></code> object.  <code class="docutils literal notranslate"><span class="pre">Pow</span></code> is short for
“power”.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&quot;Pow(Symbol(&#39;x&#39;), Integer(2))&quot;</span>
</pre></div>
</div>
<p>We could have created the same object by calling <code class="docutils literal notranslate"><span class="pre">Pow(x,</span> <span class="pre">2)</span></code></p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Pow</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">x**2</span>
</pre></div>
</div>
<p>Note that in the <code class="docutils literal notranslate"><span class="pre">srepr</span></code> output, we see <code class="docutils literal notranslate"><span class="pre">Integer(2)</span></code>, the SymPy version of
integers, even though technically, we input <code class="docutils literal notranslate"><span class="pre">2</span></code>, a Python int.  In general,
whenever you combine a SymPy object with a non-SymPy object via some function
or operation, the non-SymPy object will be converted into a SymPy object.  The
function that does this is <code class="docutils literal notranslate"><span class="pre">sympify</span></code> <a class="footnote-reference brackets" href="#sympify-fn" id="id2">2</a>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&lt;... &#39;int&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">sympify</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="go">&lt;class &#39;sympy.core.numbers.Integer&#39;&gt;</span>
</pre></div>
</div>
<p>We have seen that <code class="docutils literal notranslate"><span class="pre">x**2</span></code> is represented as <code class="docutils literal notranslate"><span class="pre">Pow(x,</span> <span class="pre">2)</span></code>.  What about
<code class="docutils literal notranslate"><span class="pre">x*y</span></code>?  As we might expect, this is the multiplication of <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code>.
The SymPy class for multiplication is <code class="docutils literal notranslate"><span class="pre">Mul</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="p">)</span>
<span class="go">&quot;Mul(Symbol(&#39;x&#39;), Symbol(&#39;y&#39;))&quot;</span>
</pre></div>
</div>
<p>Thus, we could have created the same object by writing <code class="docutils literal notranslate"><span class="pre">Mul(x,</span> <span class="pre">y)</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Mul</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="go">x*y</span>
</pre></div>
</div>
<p>Now we get to our final expression, <code class="docutils literal notranslate"><span class="pre">x**2</span> <span class="pre">+</span> <span class="pre">x*y</span></code>.  This is the addition of
our last two objects, <code class="docutils literal notranslate"><span class="pre">Pow(x,</span> <span class="pre">2)</span></code>, and <code class="docutils literal notranslate"><span class="pre">Mul(x,</span> <span class="pre">y)</span></code>.  The SymPy class for
addition is <code class="docutils literal notranslate"><span class="pre">Add</span></code>, so, as you might expect, to create this object, we use
<code class="docutils literal notranslate"><span class="pre">Add(Pow(x,</span> <span class="pre">2),</span> <span class="pre">Mul(x,</span> <span class="pre">y))</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Add</span><span class="p">(</span><span class="n">Pow</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">Mul</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="go">x**2 + x*y</span>
</pre></div>
</div>
<p>SymPy expression trees can have many branches, and can be quite deep or quite
broad.  Here is a more complicated example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="p">)</span><span class="o">/</span><span class="mi">2</span> <span class="o">-</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="mi">1</span><span class="o">/</span><span class="n">y</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="go">&quot;Add(Mul(Integer(-1), Pow(Symbol(&#39;x&#39;), Integer(2))), Mul(Rational(1, 2),</span>
<span class="go">sin(Mul(Symbol(&#39;x&#39;), Symbol(&#39;y&#39;)))), Pow(Symbol(&#39;y&#39;), Integer(-1)))&quot;</span>
</pre></div>
</div>
<p>Here is a diagram</p>
<div class="graphviz"><object data="../_images/graphviz-54ddf0a95326d32e84e72798288dc3762214049f.svg" type="image/svg+xml" class="graphviz">
<p class="warning">digraph{

# Graph style
&quot;rankdir&quot;=&quot;TD&quot;

#########
# Nodes #
#########

&quot;Half()_(0, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Rational(1, 2)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(y)_(2, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('y')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(x)_(1, 1, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Integer(2)_(1, 1, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(2)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;NegativeOne()_(2, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(-1)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;NegativeOne()_(1, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(-1)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(y)_(0, 1, 0, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('y')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(x)_(0, 1, 0, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Pow(Symbol(x), Integer(2))_(1, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Pow&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Pow(Symbol(y), NegativeOne())_(2,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Pow&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(Symbol(x), Symbol(y))_(0, 1, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;sin(Mul(Symbol(x), Symbol(y)))_(0, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;sin&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Add&quot;, &quot;shape&quot;=&quot;ellipse&quot;];

#########
# Edges #
#########

&quot;Pow(Symbol(y), NegativeOne())_(2,)&quot; -&gt; &quot;Symbol(y)_(2, 0)&quot;;
&quot;Pow(Symbol(x), Integer(2))_(1, 1)&quot; -&gt; &quot;Symbol(x)_(1, 1, 0)&quot;;
&quot;Pow(Symbol(x), Integer(2))_(1, 1)&quot; -&gt; &quot;Integer(2)_(1, 1, 1)&quot;;
&quot;Pow(Symbol(y), NegativeOne())_(2,)&quot; -&gt; &quot;NegativeOne()_(2, 1)&quot;;
&quot;Mul(Symbol(x), Symbol(y))_(0, 1, 0)&quot; -&gt; &quot;Symbol(x)_(0, 1, 0, 0)&quot;;
&quot;Mul(Symbol(x), Symbol(y))_(0, 1, 0)&quot; -&gt; &quot;Symbol(y)_(0, 1, 0, 1)&quot;;
&quot;Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)&quot; -&gt; &quot;Half()_(0, 0)&quot;;
&quot;Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)&quot; -&gt; &quot;NegativeOne()_(1, 0)&quot;;
&quot;sin(Mul(Symbol(x), Symbol(y)))_(0, 1)&quot; -&gt; &quot;Mul(Symbol(x), Symbol(y))_(0, 1, 0)&quot;;
&quot;Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)&quot; -&gt; &quot;Pow(Symbol(x), Integer(2))_(1, 1)&quot;;
&quot;Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)&quot; -&gt; &quot;sin(Mul(Symbol(x), Symbol(y)))_(0, 1)&quot;;
&quot;Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()&quot; -&gt; &quot;Pow(Symbol(y), NegativeOne())_(2,)&quot;;
&quot;Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()&quot; -&gt; &quot;Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)&quot;;
&quot;Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()&quot; -&gt; &quot;Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)&quot;;
}</p></object></div>
<p>This expression reveals some interesting things about SymPy expression
trees. Let’s go through them one by one.</p>
<p>Let’s first look at the term <code class="docutils literal notranslate"><span class="pre">x**2</span></code>.  As we expected, we see <code class="docutils literal notranslate"><span class="pre">Pow(x,</span> <span class="pre">2)</span></code>.
One level up, we see we have <code class="docutils literal notranslate"><span class="pre">Mul(-1,</span> <span class="pre">Pow(x,</span> <span class="pre">2))</span></code>.  There is no subtraction
class in SymPy.  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code> is represented as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">-y</span></code>, or, more completely,
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">-1*y</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">Add(x,</span> <span class="pre">Mul(-1,</span> <span class="pre">y))</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">x</span> <span class="o">-</span> <span class="n">y</span><span class="p">)</span>
<span class="go">&quot;Add(Symbol(&#39;x&#39;), Mul(Integer(-1), Symbol(&#39;y&#39;)))&quot;</span>
</pre></div>
</div>
<div class="graphviz"><object data="../_images/graphviz-5db6e084b5324a156050a50f98fd32d5de3830b5.svg" type="image/svg+xml" class="graphviz">
<p class="warning">digraph{

# Graph style
&quot;rankdir&quot;=&quot;TD&quot;

#########
# Nodes #
#########

&quot;Symbol(x)_(1,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(y)_(0, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('y')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;NegativeOne()_(0, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(-1)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(NegativeOne(), Symbol(y))_(0,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Add&quot;, &quot;shape&quot;=&quot;ellipse&quot;];

#########
# Edges #
#########

&quot;Mul(NegativeOne(), Symbol(y))_(0,)&quot; -&gt; &quot;Symbol(y)_(0, 1)&quot;;
&quot;Mul(NegativeOne(), Symbol(y))_(0,)&quot; -&gt; &quot;NegativeOne()_(0, 0)&quot;;
&quot;Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()&quot; -&gt; &quot;Symbol(x)_(1,)&quot;;
&quot;Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()&quot; -&gt; &quot;Mul(NegativeOne(), Symbol(y))_(0,)&quot;;
}</p></object></div>
<p>Next, look at <code class="docutils literal notranslate"><span class="pre">1/y</span></code>.  We might expect to see something like <code class="docutils literal notranslate"><span class="pre">Div(1,</span> <span class="pre">y)</span></code>,
but similar to subtraction, there is no class in SymPy for division.  Rather,
division is represented by a power of -1.  Hence, we have <code class="docutils literal notranslate"><span class="pre">Pow(y,</span> <span class="pre">-1)</span></code>.
What if we had divided something other than 1 by <code class="docutils literal notranslate"><span class="pre">y</span></code>, like <code class="docutils literal notranslate"><span class="pre">x/y</span></code>?  Let’s
see.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">x</span><span class="o">/</span><span class="n">y</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">srepr</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="go">&quot;Mul(Symbol(&#39;x&#39;), Pow(Symbol(&#39;y&#39;), Integer(-1)))&quot;</span>
</pre></div>
</div>
<div class="graphviz"><object data="../_images/graphviz-bdb16b2f7e291438d35e7ae6af6ca802a803b28c.svg" type="image/svg+xml" class="graphviz">
<p class="warning">digraph{

# Graph style
&quot;rankdir&quot;=&quot;TD&quot;

#########
# Nodes #
#########

&quot;Symbol(x)_(0,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('x')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Symbol(y)_(1, 0)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Symbol('y')&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;NegativeOne()_(1, 1)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Integer(-1)&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Pow(Symbol(y), NegativeOne())_(1,)&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Pow&quot;, &quot;shape&quot;=&quot;ellipse&quot;];
&quot;Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()&quot; [&quot;color&quot;=&quot;black&quot;, &quot;label&quot;=&quot;Mul&quot;, &quot;shape&quot;=&quot;ellipse&quot;];

#########
# Edges #
#########

&quot;Pow(Symbol(y), NegativeOne())_(1,)&quot; -&gt; &quot;Symbol(y)_(1, 0)&quot;;
&quot;Pow(Symbol(y), NegativeOne())_(1,)&quot; -&gt; &quot;NegativeOne()_(1, 1)&quot;;
&quot;Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()&quot; -&gt; &quot;Symbol(x)_(0,)&quot;;
&quot;Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()&quot; -&gt; &quot;Pow(Symbol(y), NegativeOne())_(1,)&quot;;
}</p></object></div>
<p>We see that <code class="docutils literal notranslate"><span class="pre">x/y</span></code> is represented as <code class="docutils literal notranslate"><span class="pre">x*y**-1</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">Mul(x,</span> <span class="pre">Pow(y,</span>
<span class="pre">-1))</span></code>.</p>
<p>Finally, let’s look at the <code class="docutils literal notranslate"><span class="pre">sin(x*y)/2</span></code> term.  Following the pattern of the
previous example, we might expect to see <code class="docutils literal notranslate"><span class="pre">Mul(sin(x*y),</span> <span class="pre">Pow(Integer(2),</span>
<span class="pre">-1))</span></code>.  But instead, we have <code class="docutils literal notranslate"><span class="pre">Mul(Rational(1,</span> <span class="pre">2),</span> <span class="pre">sin(x*y))</span></code>.  Rational
numbers are always combined into a single term in a multiplication, so that
when we divide by 2, it is represented as multiplying by 1/2.</p>
<p>Finally, one last note.  You may have noticed that the order we entered our
expression and the order that it came out from <code class="docutils literal notranslate"><span class="pre">srepr</span></code> or in the graph were
different.  You may have also noticed this phenomenon earlier in the
tutorial.  For example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">+</span> <span class="n">x</span>
<span class="go">x + 1</span>
</pre></div>
</div>
<p>This because in SymPy, the arguments of the commutative operations <code class="docutils literal notranslate"><span class="pre">Add</span></code> and
<code class="docutils literal notranslate"><span class="pre">Mul</span></code> are stored in an arbitrary (but consistent!) order, which is
independent of the order inputted (if you’re worried about noncommutative
multiplication, don’t be.  In SymPy, you can create noncommutative Symbols
using <code class="docutils literal notranslate"><span class="pre">Symbol('A',</span> <span class="pre">commutative=False)</span></code>, and the order of multiplication for
noncommutative Symbols is kept the same as the input).  Furthermore, as we
shall see in the next section, the printing order and the order in which
things are stored internally need not be the same either.</p>
<aside class="sidebar">
<p class="sidebar-title">Quick Tip</p>
<p>The way an expression is represented internally and the way it is printed
are often not the same.</p>
</aside>
<p>In general, an important thing to keep in mind when working with SymPy expression
trees is this:  the internal representation of an expression and the way it is
printed need not be the same.  The same is true for the input form.   If some
expression manipulation algorithm is not working in the way you expected it
to, chances are, the internal representation of the object is different from
what you thought it was.</p>
</section>
<section id="recursing-through-an-expression-tree">
<h2>Recursing through an Expression Tree<a class="headerlink" href="#recursing-through-an-expression-tree" title="Permalink to this headline">¶</a></h2>
<p>Now that you know how expression trees work in SymPy, let’s look at how to dig
our way through an expression tree.  Every object in SymPy has two very
important attributes, <code class="docutils literal notranslate"><span class="pre">func</span></code>, and <code class="docutils literal notranslate"><span class="pre">args</span></code>.</p>
<section id="func">
<h3>func<a class="headerlink" href="#func" title="Permalink to this headline">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">func</span></code> is the head of the object. For example, <code class="docutils literal notranslate"><span class="pre">(x*y).func</span></code> is <code class="docutils literal notranslate"><span class="pre">Mul</span></code>.
Usually it is the same as the class of the object (though there are exceptions
to this rule).</p>
<p>Two notes about <code class="docutils literal notranslate"><span class="pre">func</span></code>.  First, the class of an object need not be the same
as the one used to create it.  For example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">Add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">func</span>
<span class="go">&lt;class &#39;sympy.core.mul.Mul&#39;&gt;</span>
</pre></div>
</div>
<p>We created <code class="docutils literal notranslate"><span class="pre">Add(x,</span> <span class="pre">x)</span></code>, so we might expect <code class="docutils literal notranslate"><span class="pre">expr.func</span></code> to be <code class="docutils literal notranslate"><span class="pre">Add</span></code>, but
instead we got <code class="docutils literal notranslate"><span class="pre">Mul</span></code>.  Why is that?  Let’s take a closer look at <code class="docutils literal notranslate"><span class="pre">expr</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span>
<span class="go">2*x</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Add(x,</span> <span class="pre">x)</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">x</span></code>, was automatically converted into <code class="docutils literal notranslate"><span class="pre">Mul(2,</span>
<span class="pre">x)</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">2*x</span></code>, which is a <code class="docutils literal notranslate"><span class="pre">Mul</span></code>.   SymPy classes make heavy use of the
<code class="docutils literal notranslate"><span class="pre">__new__</span></code> class constructor, which, unlike <code class="docutils literal notranslate"><span class="pre">__init__</span></code>, allows a different
class to be returned from the constructor.</p>
<p>Second, some classes are special-cased, usually for efficiency reasons
<a class="footnote-reference brackets" href="#singleton-fn" id="id3">3</a>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Integer</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">func</span>
<span class="go">&lt;class &#39;sympy.core.numbers.Integer&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Integer</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">func</span>
<span class="go">&lt;class &#39;sympy.core.numbers.Zero&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Integer</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">func</span>
<span class="go">&lt;class &#39;sympy.core.numbers.NegativeOne&#39;&gt;</span>
</pre></div>
</div>
<p>For the most part, these issues will not bother us.  The special classes
<code class="docutils literal notranslate"><span class="pre">Zero</span></code>, <code class="docutils literal notranslate"><span class="pre">One</span></code>, <code class="docutils literal notranslate"><span class="pre">NegativeOne</span></code>, and so on are subclasses of <code class="docutils literal notranslate"><span class="pre">Integer</span></code>,
so as long as you use <code class="docutils literal notranslate"><span class="pre">isinstance</span></code>, it will not be an issue.</p>
</section>
<section id="args">
<h3>args<a class="headerlink" href="#args" title="Permalink to this headline">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">args</span></code> are the top-level arguments of the object.  <code class="docutils literal notranslate"><span class="pre">(x*y).args</span></code> would be
<code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code>.  Let’s look at some examples</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="mi">3</span><span class="o">*</span><span class="n">y</span><span class="o">**</span><span class="mi">2</span><span class="o">*</span><span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">func</span>
<span class="go">&lt;class &#39;sympy.core.mul.Mul&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">args</span>
<span class="go">(3, x, y**2)</span>
</pre></div>
</div>
<p>From this, we can see that <code class="docutils literal notranslate"><span class="pre">expr</span> <span class="pre">==</span> <span class="pre">Mul(3,</span> <span class="pre">y**2,</span> <span class="pre">x)</span></code>.  In fact, we can see
that we can completely reconstruct <code class="docutils literal notranslate"><span class="pre">expr</span></code> from its <code class="docutils literal notranslate"><span class="pre">func</span></code> and its
<code class="docutils literal notranslate"><span class="pre">args</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">expr</span><span class="o">.</span><span class="n">args</span><span class="p">)</span>
<span class="go">3*x*y**2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">==</span> <span class="n">expr</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">expr</span><span class="o">.</span><span class="n">args</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Note that although we entered <code class="docutils literal notranslate"><span class="pre">3*y**2*x</span></code>, the <code class="docutils literal notranslate"><span class="pre">args</span></code> are <code class="docutils literal notranslate"><span class="pre">(3,</span> <span class="pre">x,</span> <span class="pre">y**2)</span></code>.
In a <code class="docutils literal notranslate"><span class="pre">Mul</span></code>, the Rational coefficient will come first in the <code class="docutils literal notranslate"><span class="pre">args</span></code>, but
other than that, the order of everything else follows no special pattern.  To
be sure, though, there is an order.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">y</span><span class="o">**</span><span class="mi">2</span><span class="o">*</span><span class="mi">3</span><span class="o">*</span><span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">args</span>
<span class="go">(3, x, y**2)</span>
</pre></div>
</div>
<p>Mul’s <code class="docutils literal notranslate"><span class="pre">args</span></code> are sorted, so that the same <code class="docutils literal notranslate"><span class="pre">Mul</span></code> will have the same
<code class="docutils literal notranslate"><span class="pre">args</span></code>.  But the sorting is based on some criteria designed to make the
sorting unique and efficient that has no mathematical significance.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">srepr</span></code> form of our <code class="docutils literal notranslate"><span class="pre">expr</span></code> is <code class="docutils literal notranslate"><span class="pre">Mul(3,</span> <span class="pre">x,</span> <span class="pre">Pow(y,</span> <span class="pre">2))</span></code>.  What if we
want to get at the <code class="docutils literal notranslate"><span class="pre">args</span></code> of <code class="docutils literal notranslate"><span class="pre">Pow(y,</span> <span class="pre">2)</span></code>.  Notice that the <code class="docutils literal notranslate"><span class="pre">y**2</span></code> is in
the third slot of <code class="docutils literal notranslate"><span class="pre">expr.args</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">expr.args[2]</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
<span class="go">y**2</span>
</pre></div>
</div>
<p>So to get the <code class="docutils literal notranslate"><span class="pre">args</span></code> of this, we call <code class="docutils literal notranslate"><span class="pre">expr.args[2].args</span></code>.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">args</span>
<span class="go">(y, 2)</span>
</pre></div>
</div>
<p>Now what if we try to go deeper.  What are the args of <code class="docutils literal notranslate"><span class="pre">y</span></code>.  Or <code class="docutils literal notranslate"><span class="pre">2</span></code>.
Let’s see.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">args</span>
<span class="go">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Integer</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">args</span>
<span class="go">()</span>
</pre></div>
</div>
<p>They both have empty <code class="docutils literal notranslate"><span class="pre">args</span></code>.  In SymPy, empty <code class="docutils literal notranslate"><span class="pre">args</span></code> signal that we have
hit a leaf of the expression tree.</p>
<p>So there are two possibilities for a SymPy expression. Either it has empty
<code class="docutils literal notranslate"><span class="pre">args</span></code>, in which case it is a leaf node in any expression tree, or it has
<code class="docutils literal notranslate"><span class="pre">args</span></code>, in which case, it is a branch node of any expression tree.  When it
has <code class="docutils literal notranslate"><span class="pre">args</span></code>, it can be completely rebuilt from its <code class="docutils literal notranslate"><span class="pre">func</span></code> and its <code class="docutils literal notranslate"><span class="pre">args</span></code>.
This is expressed in the key invariant.</p>
<div class="topic">
<p class="topic-title">Key Invariant</p>
<p>Every well-formed SymPy expression must either have empty <code class="docutils literal notranslate"><span class="pre">args</span></code> or
satisfy <code class="docutils literal notranslate"><span class="pre">expr</span> <span class="pre">==</span> <span class="pre">expr.func(*expr.args)</span></code>.</p>
</div>
<p>(Recall that in Python if <code class="docutils literal notranslate"><span class="pre">a</span></code> is a tuple, then <code class="docutils literal notranslate"><span class="pre">f(*a)</span></code> means to call <code class="docutils literal notranslate"><span class="pre">f</span></code>
with arguments from the elements of <code class="docutils literal notranslate"><span class="pre">a</span></code>, e.g., <code class="docutils literal notranslate"><span class="pre">f(*(1,</span> <span class="pre">2,</span> <span class="pre">3))</span></code> is the same
as <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code>.)</p>
<p>This key invariant allows us to write simple algorithms that walk expression
trees, change them, and rebuild them into new expressions.</p>
</section>
<section id="walking-the-tree">
<h3>Walking the Tree<a class="headerlink" href="#walking-the-tree" title="Permalink to this headline">¶</a></h3>
<p>With this knowledge, let’s look at how we can recurse through an expression
tree.  The nested nature of <code class="docutils literal notranslate"><span class="pre">args</span></code> is a perfect fit for recursive functions.
The base case will be empty <code class="docutils literal notranslate"><span class="pre">args</span></code>.  Let’s write a simple function that goes
through an expression and prints all the <code class="docutils literal notranslate"><span class="pre">args</span></code> at each level.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">pre</span><span class="p">(</span><span class="n">expr</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">expr</span><span class="o">.</span><span class="n">args</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">pre</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
</pre></div>
</div>
<p>See how nice it is that <code class="docutils literal notranslate"><span class="pre">()</span></code> signals leaves in the expression tree.  We
don’t even have to write a base case for our recursion; it is handled
automatically by the for loop.</p>
<p>Let’s test our function.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="o">+</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pre</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="go">x*y + 1</span>
<span class="go">1</span>
<span class="go">x*y</span>
<span class="go">x</span>
<span class="go">y</span>
</pre></div>
</div>
<p>Can you guess why we called our function <code class="docutils literal notranslate"><span class="pre">pre</span></code>?  We just wrote a pre-order
traversal function for our expression tree.   See if you can write a
post-order traversal function.</p>
<p>Such traversals are so common in SymPy that the generator functions
<code class="docutils literal notranslate"><span class="pre">preorder_traversal</span></code> and <code class="docutils literal notranslate"><span class="pre">postorder_traversal</span></code> are provided to make such
traversals easy.  We could have also written our algorithm as</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">preorder_traversal</span><span class="p">(</span><span class="n">expr</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="go">x*y + 1</span>
<span class="go">1</span>
<span class="go">x*y</span>
<span class="go">x</span>
<span class="go">y</span>
</pre></div>
</div>
</section>
</section>
<section id="prevent-expression-evaluation">
<h2>Prevent expression evaluation<a class="headerlink" href="#prevent-expression-evaluation" title="Permalink to this headline">¶</a></h2>
<p>There are generally two ways to prevent the evaluation, either pass an
<code class="docutils literal notranslate"><span class="pre">evaluate=False</span></code> parameter while constructing the expression, or create
an evaluation stopper by wrapping the expression with <code class="docutils literal notranslate"><span class="pre">UnevaluatedExpr</span></code>.</p>
<p>For example:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="n">Add</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy.abc</span> <span class="kn">import</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">+</span> <span class="n">x</span>
<span class="go">2*x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="go">2*x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">x + x</span>
</pre></div>
</div>
<p>If you don’t remember the class corresponding to the expression you
want to build (operator overloading usually assumes <code class="docutils literal notranslate"><span class="pre">evaluate=True</span></code>),
just use <code class="docutils literal notranslate"><span class="pre">sympify</span></code> and pass a string:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="n">sympify</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sympify</span><span class="p">(</span><span class="s2">&quot;x + x&quot;</span><span class="p">,</span> <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">x + x</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">evaluate=False</span></code> won’t prevent future evaluation in later
usages of the expression:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">Add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span>
<span class="go">x + x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">+</span> <span class="n">x</span>
<span class="go">3*x</span>
</pre></div>
</div>
<p>That’s why the class <code class="docutils literal notranslate"><span class="pre">UnevaluatedExpr</span></code> comes handy.
<code class="docutils literal notranslate"><span class="pre">UnevaluatedExpr</span></code> is a method provided by SymPy which lets the user keep
an expression unevaluated. By <em>unevaluated</em> it is meant that the value
inside of it will not interact with the expressions outside of it to give
simplified outputs. For example:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="n">UnevaluatedExpr</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span>
<span class="go">x + x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">+</span> <span class="n">expr</span>
<span class="go">2*x + x</span>
</pre></div>
</div>
<p>The <span class="math notranslate nohighlight">\(x\)</span> remaining alone is the <span class="math notranslate nohighlight">\(x\)</span> wrapped by <code class="docutils literal notranslate"><span class="pre">UnevaluatedExpr</span></code>.
To release it:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">x</span> <span class="o">+</span> <span class="n">expr</span><span class="p">)</span><span class="o">.</span><span class="n">doit</span><span class="p">()</span>
<span class="go">3*x</span>
</pre></div>
</div>
<p>Other examples:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy.abc</span> <span class="kn">import</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uexpr</span> <span class="o">=</span> <span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">S</span><span class="o">.</span><span class="n">One</span><span class="o">*</span><span class="mi">5</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span><span class="o">*</span><span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">S</span><span class="o">.</span><span class="n">One</span><span class="o">*</span><span class="mi">3</span><span class="o">/</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uexpr</span>
<span class="go">(5/7)*(3/4)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">*</span><span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="n">x</span><span class="p">)</span>
<span class="go">x*1/x</span>
</pre></div>
</div>
<p>A point to be noted is that  <code class="docutils literal notranslate"><span class="pre">UnevaluatedExpr</span></code> cannot prevent the
evaluation of an expression which is given as argument. For example:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr1</span> <span class="o">=</span> <span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">x</span> <span class="o">+</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr1</span>
<span class="go">2*x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr2</span> <span class="o">=</span> <span class="n">sympify</span><span class="p">(</span><span class="s1">&#39;x + x&#39;</span><span class="p">,</span> <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr2</span>
<span class="go">x + x</span>
</pre></div>
</div>
<p>Remember that <code class="docutils literal notranslate"><span class="pre">expr2</span></code> will be evaluated if included into another
expression. Combine both of the methods to prevent both inside and outside
evaluations:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">sympify</span><span class="p">(</span><span class="s2">&quot;x + x&quot;</span><span class="p">,</span> <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">))</span> <span class="o">+</span> <span class="n">y</span>
<span class="go">y + x + x</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">UnevalutedExpr</span></code> is supported by SymPy printers and can be used to print the
result in different output forms. For example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="n">latex</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uexpr</span> <span class="o">=</span> <span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">S</span><span class="o">.</span><span class="n">One</span><span class="o">*</span><span class="mi">5</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span><span class="o">*</span><span class="n">UnevaluatedExpr</span><span class="p">(</span><span class="n">S</span><span class="o">.</span><span class="n">One</span><span class="o">*</span><span class="mi">3</span><span class="o">/</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">latex</span><span class="p">(</span><span class="n">uexpr</span><span class="p">))</span>
<span class="go">\frac{5}{7} \frac{3}{4}</span>
</pre></div>
</div>
<p>In order to release the expression and get the evaluated LaTeX form,
just use <code class="docutils literal notranslate"><span class="pre">.doit()</span></code>:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">latex</span><span class="p">(</span><span class="n">uexpr</span><span class="o">.</span><span class="n">doit</span><span class="p">()))</span>
<span class="go">\frac{15}{28}</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="symbols-fn"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>We have been using <code class="docutils literal notranslate"><span class="pre">symbols</span></code> instead of <code class="docutils literal notranslate"><span class="pre">Symbol</span></code> because it
automatically splits apart strings into multiple <code class="docutils literal notranslate"><span class="pre">Symbol</span></code>s.
<code class="docutils literal notranslate"><span class="pre">symbols('x</span> <span class="pre">y</span> <span class="pre">z')</span></code> returns a tuple of three <code class="docutils literal notranslate"><span class="pre">Symbol</span></code>s.  <code class="docutils literal notranslate"><span class="pre">Symbol('x</span> <span class="pre">y</span>
<span class="pre">z')</span></code> returns a single <code class="docutils literal notranslate"><span class="pre">Symbol</span></code> called <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">y</span> <span class="pre">z</span></code>.</p>
</dd>
<dt class="label" id="sympify-fn"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
<dd><p>Technically, it is an internal function called <code class="docutils literal notranslate"><span class="pre">_sympify</span></code>,
which differs from <code class="docutils literal notranslate"><span class="pre">sympify</span></code> in that it does not convert strings.  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span>
<span class="pre">'2'</span></code> is not allowed.</p>
</dd>
<dt class="label" id="singleton-fn"><span class="brackets"><a class="fn-backref" href="#id3">3</a></span></dt>
<dd><p>Classes like <code class="docutils literal notranslate"><span class="pre">One</span></code> and <code class="docutils literal notranslate"><span class="pre">Zero</span></code> are singletonized, meaning
that only one object is ever created, no matter how many times the class is
called.  This is done for space efficiency, as these classes are very
common.  For example, <code class="docutils literal notranslate"><span class="pre">Zero</span></code> might occur very often in a sparse matrix
represented densely.  As we have seen, <code class="docutils literal notranslate"><span class="pre">NegativeOne</span></code> occurs any time we
have <code class="docutils literal notranslate"><span class="pre">-x</span></code> or <code class="docutils literal notranslate"><span class="pre">1/x</span></code>.  It is also done for speed efficiency because
singletonized objects can be compared by <code class="docutils literal notranslate"><span class="pre">is</span></code>.  The unique objects for
each singletonized class can be accessed from the <code class="docutils literal notranslate"><span class="pre">S</span></code> object.</p>
</dd>
</dl>
</section>
</section>


            <div class="clearer"></div>
          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../index.html">
              <img class="logo" src="../_static/sympylogo.png" alt="Logo"/>
            </a></p>
  <h3><a href="../index.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Advanced Expression Manipulation</a><ul>
<li><a class="reference internal" href="#understanding-expression-trees">Understanding Expression Trees</a></li>
<li><a class="reference internal" href="#recursing-through-an-expression-tree">Recursing through an Expression Tree</a><ul>
<li><a class="reference internal" href="#func">func</a></li>
<li><a class="reference internal" href="#args">args</a></li>
<li><a class="reference internal" href="#walking-the-tree">Walking the Tree</a></li>
</ul>
</li>
<li><a class="reference internal" href="#prevent-expression-evaluation">Prevent expression evaluation</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="matrices.html"
                        title="previous chapter">Matrices</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../guides/index.html"
                        title="next chapter">SymPy Guides</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/manipulation.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="https://docs.sympy.org/latest/search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script>$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../guides/index.html" title="SymPy Guides"
             >next</a> |</li>
        <li class="right" >
          <a href="matrices.html" title="Matrices"
             >previous</a> |</li>
        <li class="nav-item nav-item-0"><a href="../index.html">SymPy 1.9 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="index.html" >SymPy Tutorial</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="#">Advanced Expression Manipulation</a></li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2021 SymPy Development Team.
      Last updated on Sep 30, 2021.
      Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.1.2.
    </div>
  </body>

<!-- Mirrored from docs.sympy.org/latest/tutorial/manipulation.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 15 Jan 2022 03:23:59 GMT -->
</html>